// 异步加载百度地图
let promise;

let count = 0
// let libs = [
//     'http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js',
//     'http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js',
//     'http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js'
// ]
let libs = [
  'http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js'
]
const head = document.getElementsByTagName('head')[0]


function loadLib(src, resolve, reject) {
    const lib = document.createElement('script');
    lib.setAttribute('type', 'text/javascript');
    lib.setAttribute('src', src);
    lib.onerror = function() {
        reject('地图初始化失败');
    }
    lib.onload = function() {
        count += 1;
        if (count === libs.length) { // libs全部加载成功才返回
            resolve({BMap: window.BMap, BMapLib: window.BMapLib});
        }
    }
    head.appendChild(lib);
}

export default function loadBMap(ak) {
    if (promise) return promise;
    promise = new Promise((resolve, reject) => {
        if (window.BMap && window.BMapLib) {
            // 已经加载则直接返回
            console.log('map already exist');
            resolve({BMap: window.BMap, BMapLib: window.BMapLib});
        } else {
            // 异步加载
            // console.log('async load map');
            const bmap = document.createElement('script');
            bmap.type = 'text/javascript';
            bmap.src = 'http://api.map.baidu.com/api?v=3.0&ak=' + ak + '&callback=MapLoadSuccess';
            head.appendChild(bmap);
            window.MapLoadSuccess = function() {
                // BMap加载完成，开始加载libs
                libs.forEach(lib => {
                    loadLib(lib, resolve, reject);
                })
            }
            bmap.onerror = function() {
                reject('地图初始化失败');
            }
        }
    })
    return promise;
}